package com.rainszj.controller.site;

import com.rainszj.pojo.po.Comment;
import com.rainszj.pojo.po.User;
import com.rainszj.service.BlogService;
import com.rainszj.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Arrays;
import java.util.List;

/**
 * 博客评论
 *
 * @author rainszj
 * 2020/3/21
 */
@Slf4j
@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    /**
     * 访客评论的头像
     */
    @Value("${comment.avatar}")
    private String avatar;

    /**
     * 评论下作者的昵称
     */
    @Value("${comment.author}")
    private String author;

    /**
     * 列出二级评论列表
     *
     * @param blogId
     * @param model
     * @return
     */
    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable("blogId") Long blogId, Model model) {
        List<Comment> comments = commentService.listCommentByBlogId(blogId);
        model.addAttribute("comments", comments);

        return "site/blog::commentList";
    }


    /**
     * 保存评论并跳转到显示评论
     *
     * @param comment
     * @return
     */
    @PostMapping("/comments")
    public String post(Comment comment) {
        log.info(comment.toString());
        Long blogId = comment.getBlogId();

        Subject subject = SecurityUtils.getSubject();
        User loginUser = (User) subject.getSession().getAttribute("loginUser");
        if (loginUser != null) {
            // 管理员登录
            comment.setAvatar(loginUser.getAvatar());
            comment.setAdminComment(true);
            comment.setNickname(author);
        } else {
            // 普通用户
            comment.setAvatar(avatar);
        }

        commentService.saveComment(comment);
        return "redirect:/comments/" + blogId;
    }

}
